<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { AppApi } from '#/api/core/app';
import type { SpaceApi } from '#/api/core/space';

import { onMounted, ref, watch } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { Button, Empty, message, Modal, Select } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteApp, getAppListByPage } from '#/api/core/app';
import { $t } from '#/locales';
import { useTableForgeStore } from '#/store/tableforge';

import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

const tableForgeStore = useTableForgeStore();

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    fieldMappingTime: [['createdTime', ['startTime', 'endTime']]],
    schema: useGridFormSchema(),
    submitOnChange: true,
  },
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          if (!tableForgeStore.currentSpaceId) {
            return { items: [], total: 0 };
          }
          try {
            return await getAppListByPage(tableForgeStore.currentSpaceId, {
              pageNum: page.currentPage,
              pageSize: page.pageSize,
              orderBy: 'createdTime',
              orderDirection: 'desc',
              ...formValues,
            });
          } catch (error) {
            console.error('获取应用列表失败', error);
            return { items: [], total: 0 };
          }
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
  } as VxeTableGridOptions<AppApi.App>,
});

// 空间选择器
const spaceOptions = ref<{ label: string; value: string }[]>([]);
const selectedSpaceId = ref('');

// 监听空间变化
watch(
  () => selectedSpaceId.value,
  (newVal) => {
    if (newVal) {
      tableForgeStore.setCurrentSpace(newVal);
      gridApi.reload();
    }
  },
);

// 加载空间列表
async function loadSpaces() {
  const spaces = await tableForgeStore.fetchSpaceList();
  spaceOptions.value = spaces.map((space: SpaceApi.Space) => ({
    label: space.name,
    value: space.id,
  }));

  // 如果有空间，默认选中第一个
  if (spaces.length > 0 && !tableForgeStore.currentSpaceId) {
    selectedSpaceId.value = spaces[0].id;
  } else if (tableForgeStore.currentSpaceId) {
    selectedSpaceId.value = tableForgeStore.currentSpaceId;
  }
}

onMounted(() => {
  loadSpaces();
});

function onActionClick(e: OnActionClickParams<AppApi.App>) {
  switch (e.code) {
    case 'delete': {
      onDelete(e.row);
      break;
    }
    case 'edit': {
      onEdit(e.row);
      break;
    }
    case 'view': {
      onView(e.row);
      break;
    }
  }
}

/**
 * 将Antd的Modal.confirm封装为promise，方便在异步函数中调用。
 */
function confirm(content: string, title: string) {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      content,
      onCancel() {
        reject(new Error('已取消'));
      },
      onOk() {
        resolve(true);
      },
      title,
    });
  });
}

// 删除应用
async function onDelete(row: AppApi.App) {
  try {
    await confirm(
      `确定要删除应用 【${row.name}】 吗？删除后不可恢复！`,
      '删除应用',
    );
    await deleteApp(row.id);
    message.success('删除成功');
    gridApi.reload();
  } catch (error) {
    console.error('删除应用失败', error);
  }
}

// 编辑应用
function onEdit(row: AppApi.App) {
  formDrawerApi.open({
    data: row,
    title: $t('common.edit', { name: $t('tableforge.app.name') }),
    width: 500,
  });
}

// 查看应用详情
function onView(row: AppApi.App) {
  tableForgeStore.setCurrentApp(row.id);
  // 可以跳转到表格管理页面
  // router.push('/tableforge/table');
}

// 创建应用
function onCreate() {
  // 在打开表单前设置当前选中的空间ID
  const formData = {
    spaceId: selectedSpaceId.value,
  };

  formDrawerApi.open({
    data: formData,
    title: $t('common.create', { name: $t('tableforge.app.name') }),
    width: 500,
  });
}

// 表单提交成功后刷新列表
function onSuccess() {
  gridApi.reload();
}
</script>

<template>
  <Page>
    <template #headerLeft>
      <div class="flex items-center space-x-4">
        <span>所属空间：</span>
        <Select
          v-model:value="selectedSpaceId"
          :options="spaceOptions"
          placeholder="请选择空间"
          style="width: 200px"
        />
      </div>
    </template>

    <template #headerRight>
      <Button type="primary" @click="onCreate">
        <template #icon>
          <Plus />
        </template>
        {{ $t('tableforge.app.create') }}
      </Button>
    </template>

    <div
      v-if="!tableForgeStore.currentSpaceId"
      class="flex h-64 items-center justify-center"
    >
      <Empty description="请先选择空间" />
    </div>
    <Grid v-else />

    <FormDrawer @success="onSuccess" />
  </Page>
</template>
